package com.example.day26_toupinpush;

import android.media.projection.MediaProjection;
import android.util.Log;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;

/**
 * Description:
 * Created by Gdu on 2021/1/2 23:03.
 */

public class SocketLive {
    public static final String TAG = "SocketLive";
    private WebSocket webSocket;
    int port;
    CodecLiveH265 codecLiveH265;

    public SocketLive(int port) {
        this.port = port;
    }

    public void start(MediaProjection mediaProjection) {
        webSocketServer.start();
        codecLiveH265 = new CodecLiveH265(this,mediaProjection);
        codecLiveH265.startLive();
    }

    public void close() {
        try {
            webSocket.close();
            webSocketServer.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private WebSocketServer webSocketServer = new WebSocketServer(new InetSocketAddress(port)){
        @Override
        public void onOpen(WebSocket conn, ClientHandshake handshake) {
            SocketLive.this.webSocket = conn;
        }

        @Override
        public void onClose(WebSocket conn, int code, String reason, boolean remote) {
            Log.i(TAG,"onClose: 关闭 "+reason);
        }

        @Override
        public void onMessage(WebSocket conn, String message) { }

        @Override
        public void onError(WebSocket conn, Exception ex) {
            Log.i(TAG,"onError: 错误 "+ex.toString());
        }

        @Override
        public void onStart() {

        }
    };

    public void sendData(byte[] bytes){
        if (webSocket != null && webSocket.isOpen()) {
            webSocket.send(bytes);
        }
    }

}
